package com.example.sachon;

import java.io.*;
import java.nio.charset.*;
import java.text.*;

import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.entity.mime.*;
import org.apache.http.entity.mime.content.*;
import org.apache.http.impl.client.*;
import org.apache.http.util.*;

import android.media.*;
import android.net.*;
import android.os.*;
import android.provider.*;
import android.provider.MediaStore.Images;
import android.annotation.SuppressLint;
import android.app.*;
import android.content.*;
import android.content.res.*;
import android.database.*;
import android.graphics.*;
import android.text.*;
import android.text.method.*;
import android.util.*;
import android.view.*;
import android.view.inputmethod.*;
import android.widget.*;
import android.widget.TextView.OnEditorActionListener;

public class SA3400 extends Activity {

	private ImageView imageView;
	private EditText editText1;
	private static Uri imageUri;
	//디바이스에 저장되는 장소 
	public static final int REQUEST_CAMERA = 8000;
	public static final int SELECT_IMAGE = 9000;
	public static String ROOT_IMAGE_FOLDER = "";
	public static String HTTP_SERVER_DOMAIN = "http://auralizer.cafe24.com"; // "http://192.168.30.120:8080";
	private InputMethodManager imm = null;
	private ProgressDialog progressDialog;
	private final String LOGTAG = "SA3400_";
	
	// 키보드 숨기기
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sa3400);
		
		//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		//StrictMode.setThreadPolicy(policy);
		
		imageUri = null;
		
		try
		{
			/*
			Const.getInstance().chonInfo().setChon_id("1");
			Const.getInstance().chonInfo().setChon_nm("부필1리");
			Const.getInstance().chonInfo().setChon_small_img("bupil1ri.jpg");
			
			Const.getInstance().userInfo().setChon_id("1");
			Const.getInstance().userInfo().setPhone_number("01091429921");
			Const.getInstance().userInfo().setUser_lv("");
			Const.getInstance().userInfo().setUser_name("김광용");
			*/
			// setTitle(Const.getInstance().chonInfo().getChon_nm());

			ROOT_IMAGE_FOLDER = Environment.getExternalStorageDirectory().getAbsolutePath();
			
			TextView sa3400_title_txt_chon_name = (TextView) findViewById(R.id.sa3400_title_txt_chon_name);
			sa3400_title_txt_chon_name.setText(Const.getInstance().chonInfo().getChon_nm());

			imageView = (ImageView) findViewById(R.id.sa3400_imageView);
			editText1 = (EditText) findViewById(R.id.sa3400_editText1);
			ImageButton capturebutton = (ImageButton) findViewById(R.id.sa3400_imgBtnCapture);
			ImageButton SelectImageBtn = (ImageButton) findViewById(R.id.sa3400_imgBtnPicture);
			ImageView savebutton = (ImageView) findViewById(R.id.sa3400_imgBtnSave);
			ImageView sa3400_title_img_go_home = (ImageView) findViewById(R.id.sa3400_title_img_go_home);

			// 키보드 숨기기
			//imm = (InputMethodManager)SA3400.this.getSystemService(Context.INPUT_METHOD_SERVICE);
			//imm.hideSoftInputFromWindow(editText1.getWindowToken(), 0);

			// 홈으로 가기
			sa3400_title_img_go_home.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					try
					{
						Intent intent = new Intent();
						setResult(RESULT_OK, intent);
						finish();
					}
					catch(Exception e) {
						ShowAlertMsg("Exception:" + e.getMessage());
					}
				}
			});

			// 사진 가져오기
			SelectImageBtn.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					try
					{
						// Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
						Intent i = new Intent();
						i.setAction(Intent.ACTION_GET_CONTENT);
						i.setType("image/*");
						SA3400.this.startActivityForResult(i, SELECT_IMAGE);
					}
					catch(Exception e) {
						ShowAlertMsg("Exception:" + e.getMessage());
					}
				}
			});
	
	        // 사진 찍기
			capturebutton.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					try
					{
			            // 확장자 . 포함
			            String tmpName1 = String.valueOf(java.lang.Math.round(java.lang.Math.random()*1000)); // 시간으로만 파일명 생성시 중복발생하여 random숫자 추가
			            String svr_file_name = getNowDateTime(2)+ "_" + tmpName1 + ".jpg";

			            File dir = new File(ROOT_IMAGE_FOLDER+"/sachon/tmp/");
						
						if(!dir.exists()){
							dir.mkdirs();
						}
						
						
						File photo = new File(dir,svr_file_name);
						imageUri = Uri.fromFile(photo);
		
						// Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
						Intent i = new Intent();
						i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
						i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
						SA3400.this.startActivityForResult(i, REQUEST_CAMERA);
					}
					catch(Exception e) {
						ShowAlertMsg("Exception:" + e.getMessage());
					}
				}
			});
	
			// 업로드 버튼 이벤트
			savebutton.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					String imagePath = "";
					try
					{
						/*
						if(imageUri != null)
						{
							imagePath = imageUri.getPath();
						}
						else
						{
							ShowAlertMsg("선택된 이미지가 없습니다.");
						}
						*/
						
		                /*
						if(imagePath != null && imagePath.length() > 0)
						{
						}
						else
						{
							ShowAlertMsg("선택된 이미지가 없습니다.");
						}
						*/
						AlertDialog.Builder dlg= new AlertDialog.Builder(SA3400.this);
		                dlg.setTitle("선택하세요")
		                .setIcon(R.drawable.ic_launcher)
		                .setMessage("업로드 하시겠습니까?")
		                .setCancelable(false)
		                .setNegativeButton("NO", new DialogInterface.OnClickListener() {
		                	@Override
		                	public void onClick(DialogInterface dialog, int which) {
		                    }
		                })
		                .setPositiveButton("YES", new DialogInterface.OnClickListener() {
		                	@Override
		                	public void onClick(DialogInterface dialog, int which) {
		    					
	        					progressDialog = ProgressDialog.show(SA3400.this, "작성중", "잠시만기다려주세요");
	        					
	        					
	    						new Thread(){
	    							public void run() {
	    								
	    								String imagePath;
	    								File file;
				        				
				    					try{        
				    						HttpClient client = new DefaultHttpClient();        
				    						String postURL = HTTP_SERVER_DOMAIN + "/sachon/sa_board_write_ok.jsp"; // "/BoardEx01/board1/Upload_FileProcess.jsp";        
				    						HttpPost post = new HttpPost(postURL);
				    						// StringBody 
				    						MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);        
				    						
		    								if(imageUri != null)
		    								{
		    									imagePath = imageUri.getPath();
		    									if(imagePath != null && imagePath.length() > 0)
		    									{
						        					file = new File(imagePath);
						    						FileBody bin = new FileBody(file);        
						    						reqEntity.addPart("File", bin);
		    									}
		    								}
				    						
				    						StringBody chon_id = new StringBody(Const.getInstance().chonInfo().getChon_id());        
				    						reqEntity.addPart("chon_id", chon_id);        
				    						StringBody title = new StringBody("제목입니다", Charset.forName("UTF-8"));        
				    						reqEntity.addPart("title", title);         
				    						// news:소식지, jang:장터, cal:일정
				    						StringBody board_id = new StringBody("cal");
				    						reqEntity.addPart("board_id", board_id);        
				    						StringBody phone_number = new StringBody(Const.getInstance().userInfo().getPhone_number());        
				    						reqEntity.addPart("phone_number", phone_number);        
				    						StringBody passwd = new StringBody("");        
				    						reqEntity.addPart("passwd", passwd);        
				    						StringBody content = new StringBody(editText1.getText().toString(), Charset.forName("UTF-8"));        
				    						reqEntity.addPart("content", content);        
				    						StringBody view_lv = new StringBody("0");        
				    						reqEntity.addPart("view_lv", view_lv);        
				    						StringBody from_dt = new StringBody(getNowDateTime(0));        
				    						reqEntity.addPart("from_dt", from_dt);        
				    						post.setEntity(reqEntity);
				    						HttpResponse response = client.execute(post);        
				    						HttpEntity resEntity = response.getEntity();                
				    						if (resEntity != null)        
				    						{                    
				    							// Log.i("RESPONSE", EntityUtils.toString(resEntity));
				    							ShowAlertMsg("정상적으로 작성되었습니다.");
				    						}
				    						// 완료 후 이전화면으로 이동
				    						Intent intent = new Intent();
				    						setResult(RESULT_OK, intent);
				    						progressDialog.dismiss();
				    						finish();
				    					}
				    					catch (Exception e)
				    					{
				    						progressDialog.dismiss();
				    						ShowAlertMsg("Exception:" + e.getMessage());
				    					}
	    							};
	    						}.start();
		                    }
		                })
		                .create();
		                dlg.show();
					}
					catch(Exception e) {
						if(progressDialog != null){progressDialog.dismiss();}
						ShowAlertMsg("Exception:" + e.getMessage());
					}
				}
			});
		}
		catch(Exception e) {
			if(progressDialog != null){progressDialog.dismiss();}
			ShowAlertMsg("Exception:" + e.getMessage());
		}
	}
	
	private void ShowAlertMsg(String strMessage)
	{
		try
		{
			AlertDialog.Builder dlg= new AlertDialog.Builder(SA3400.this);
	        dlg.setTitle("알림")
	        .setIcon(R.drawable.ic_launcher)
	        .setMessage("Exception:" + strMessage)
	        .setCancelable(false)
	        .setNegativeButton("확인", null).create();
	        dlg.show();
		}
		catch(Exception e) {
			String strTemp = "";
			strTemp = e.getMessage();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == REQUEST_CAMERA) {
			if(resultCode == RESULT_OK) {
				try {
					String imagePath = imageUri.getPath();
					DisplayImage(imagePath);
				} 	catch(Exception e) {
					ShowAlertMsg("Exception:" + e.getMessage());
				}
			}
		}
		else if(requestCode == SELECT_IMAGE) {
			if(resultCode == RESULT_OK) {
				String strTemp = "";
				try {
					Uri uri = data.getData();
					// 이미지 정보 추출 및 표시
					strTemp = uri.toString() + "\n";
					strTemp = uri.getLastPathSegment();

					//컨텐트 프로바이더로 구성된 정보를 DB로 부터 읽어옴
 					Cursor c = getContentResolver().query(Images.Media.EXTERNAL_CONTENT_URI, null, Images.Media._ID + "=?", new String[] { uri.getLastPathSegment() }, null);

 					if (c.moveToFirst())
 					{
						//getColumnIndexOrThrow : 컬럼의 인덱스 반환
						String imageFile = c.getString(c.getColumnIndexOrThrow(Images.Media.DATA));
						File photo = new File(imageFile);
						Log.d(LOGTAG, "원본 이미지 경로 : " + imageFile );						
						Log.d(LOGTAG, "원본 이미지 용량 : " + photo.length());
						imageUri = Uri.fromFile(photo);
					}
 					String imagePath = imageUri.getPath();
 					DisplayImage(imagePath);
				} 
				catch (Exception e) {
					ShowAlertMsg("Exception:" + e.getMessage());
				}
			}
		}
	}

	
	public void DisplayImage(String imagePath)
	{
		Bitmap image, resize;
		int iSize = 1;
		
		try {
			/*
			 * Image 크기에 따라 변환 설정
			 */
			File imgFile = new File(imagePath);
			
			if(imgFile.length() >= 5000000){
				iSize = 4;
			}else if(imgFile.length() > 1000000 && imgFile.length() < 5000000){
				iSize = 2;
			}else{
				iSize = 1;
			}
			
			Log.d(LOGTAG, " inSampleSize : "+iSize);
			BitmapFactory.Options bfo = new BitmapFactory.Options();
			bfo.inSampleSize = iSize;		
			image = BitmapFactory.decodeFile(imagePath, bfo);
			
						
			ExifInterface exif = new ExifInterface(imagePath);
			int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			int exifDegree = exifOrientationToDegrees(exifOrientation);
			
			image = rotate(image, exifDegree);
			
			imageView.setImageBitmap(image);
			
			/*
			 * Image resize..
			 */
			//resize = Bitmap.createScaledBitmap(image, getDeviceWidth(), getDeviceHeight(), true);
			resize = Bitmap.createScaledBitmap(image, 640, 960, true);
			
			//Log.d(LOGTAG, " Resize Imege width : "+getDeviceWidth()+" height : "+getDeviceHeight());
			//resize = rotate(resize, exifDegree);
			
			/*
			 * resize image Upload를 위해 파일저장
			 */
			pictureSaveToFile(resize, imagePath);
			
		} 	catch(Exception e) {
			ShowAlertMsg("Exception:" + e.getMessage());
		}
		finally{
			image = null;
		}
	}
	
	public int exifOrientationToDegrees(int exifOrientation) {
		if(exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
			return 90;
		} else if(exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
			return 180;
		} else if(exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
			return 270;
		}
		return 0;
	}
	
	public Bitmap rotate(Bitmap bitmap, int degrees) {
		if(degrees != 0 && bitmap != null) 	{
			Matrix m = new Matrix();
			m.setRotate(degrees, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);
			
			try {
				Bitmap converted = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
				if(bitmap != converted) {
					bitmap.recycle();
					bitmap = converted;
				}
			} catch(OutOfMemoryError ex) {
				String strTemp = "";
				strTemp = ex.getMessage();
			}
		}
		return bitmap;
	}

	//현재날짜시분초
	public String getNowDateTime(int nType)
	{
		String strToday = "";
		try
		{
		    java.util.Date toDay = new java.util.Date();
	
		    String szType = "";
		    switch (nType)
		    {
		        case 1:
		            szType = "yyyyMMddHHmmss";
		            break;
		        case 2:
		            szType = "MMddHHmmss";
		            break;
		        default :
		            szType = "yyyy-MM-dd HH:mm:ss";
		            break;
		    }
	
		    SimpleDateFormat sdf = new SimpleDateFormat(szType);
		    strToday = sdf.format(toDay);
		}catch(Exception e)
		{
			strToday = "";
		}
	    return strToday;
	}
	
	/*
	 * Upload 시 이미지 크기 변환 후 저장
	 */
	public void pictureSaveToFile(Bitmap bm, String filePath){
		
		String upLoadFileName = "";
		String upLoadFile = "";
		int iFilePathLen, iLastLen;
		
		if(filePath.length() < 1){

		}
		
		String upLoadFilePath[] = filePath.split("/");
				
		iFilePathLen = upLoadFilePath.length;
		
		upLoadFileName = upLoadFilePath[upLoadFilePath.length - 1];

		Log.d(LOGTAG, "pictureSaveToFile :["+filePath+"] : ["+upLoadFileName+"]");
						
		File dir = new File(ROOT_IMAGE_FOLDER+"/sachon/");
		
		if(!dir.exists()){
			dir.mkdirs();
		}
		
		
		File file = new File(dir,"sa_"+upLoadFileName);
			
		FileOutputStream fos = null;
		try{
			
			fos = new FileOutputStream(file);
			if(fos != null){
				bm.compress(Bitmap.CompressFormat.JPEG, 80, fos);
				fos.flush();
				fos.close();
			}
			
		}catch(Exception e){
			Log.e(LOGTAG, e.getMessage());
		
		}
		Log.d(LOGTAG, "변환 후 이미지 용량 : "+file.length());
		
		/*
		 * 화면 Imegeview에 보여준 내용을 첨부 한다.
		 */
		imageUri = Uri.fromFile(file);
		
	}
	
	
	/*
	 * Display Width
	 */
	
	@SuppressLint("NewApi")
	private int getDeviceWidth() {
		if (12 < Build.VERSION.SDK_INT) {
			Point p = new Point();
			getWindowManager().getDefaultDisplay().getSize(p);
			return p.x;
		} else {
			return getWindowManager().getDefaultDisplay().getWidth();
		}
	}
	
	/*
	 * Display Height
	 */
	
	@SuppressLint("NewApi")
	private int getDeviceHeight() {
		if (12 < Build.VERSION.SDK_INT) {
			Point p = new Point();
			getWindowManager().getDefaultDisplay().getSize(p);
			return p.y;
		} else {
			return getWindowManager().getDefaultDisplay().getHeight();
		}
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_sa3400, menu);
		return true;
	}

	/* (non-Javadoc)
	* @see android.app.Activity#onConfigurationChanged(android.content.res.Configuration)
	*/
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}
}
